import 'dart:async';
// import 'package:app_links/app_links.dart';
import 'package:casdon/app/config/theme/app_theme.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/core/auth/auth_storage.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/logger/log_file_output.dart';
import 'package:casdon/core/utils/cache_utils.dart';
import 'package:casdon/auto_router.dart';
import 'package:casdon/modules/me/domain/enums/service_order_category.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:casdon/app/app_initializer.dart';
import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/common/route/native_route_observer.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

void main() async {
  debugProfileBuildsEnabled = true; // 跟踪构建性能
  debugProfilePaintsEnabled = true;

  // 热重载时清理旧的容器
  if (kDebugMode) {
    AppProviders.container?.dispose();
  }

  final container = ProviderContainer();
  AppProviders.initialize(container);
  // 运行应用
  runZonedGuarded(
    () {
      WidgetsFlutterBinding.ensureInitialized();
      // 初始化日志，因该在其他操作之前
      // 立即初始化日志系统
      _initLog();

      // 创建环境提供者
      final envconfig = getProvider(environmentProvider);
      // 根据环境初始化应用
      final initializer = AppInitializer(envconfig);
      initializer.init();
      runApp(ProviderScope(parent: container, child: MyApp()));
    },
    (error, stack) {
      Log.e('Zone error', error.toString(), stack);
      // 确保异常也写入文件，并避免阻塞后续日志
      unawaited(LogFileOutput().ensureAllWritten());
    },
  );
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  static const _channel = MethodChannel("native_to_flutter");
  @override
  void initState() {
    super.initState();
    _channel.setMethodCallHandler((call) async {
      if (call.method == "pushFlutterVC") {
        //device_share 设备共享
        // feed_back_help 反馈与帮助
        // device_report_repair 设备报修
        final args = Map<String, dynamic>.from(call.arguments);
        final path = args["path"] as String?;
        if (path != null) {
          // 提取 path，剩余参数作为查询参数
          final params = Map<String, String>.from(
            Map.fromEntries(
              args.entries
                  .where((e) => e.key != "path")
                  .map((e) => MapEntry(e.key, e.value?.toString() ?? '')),
            ),
          );
          // 根据 path 分发到对应的 AutoRoute
          if (path.contains('device_share_list')) {
            appRouter.push(
              DeviceShareListRoute(
                devId: params['devId'] ?? '',
                isFromNative: true,
              ),
            );
          } else if (path.contains('feed_back_help')) {
            appRouter.push(
              FeedbackPostRoute(
                devId: params['devId'] ?? '',
                isFromNative: true,
              ),
            );
          } else if (path.contains('device_report_repair')) {
            appRouter.push(
              ServiceRepairRoute(
                devId: params['devId'] ?? '',
                isFromNative: true,
              ),
            );
          } else {
            Log.w('未知的 Flutter 路由请求: $path');
          }
        }
      } else if (call.method == "popFlutterVC") {
        appRouter.maybePop();
      } else if (call.method == "canPopFlutterRoute") {
        // 供原生侧查询当前 Flutter 路由栈是否还能后退
        final topName = appRouter.stack.isNotEmpty
            ? appRouter.stack.last.name
            : '';
        final bool isGuardedRoot = topName == DeviceShareListRoute.name;
        return isGuardedRoot ? false : appRouter.canPop();
      } else if (call.method == "tuyaSessionLoss") {
        // 涂鸦 账号在其他手机登录，收到通知退出
        final ret = await showCustomConfirmDialog(
          context: context,
          title: "提示",
          content: "会话已失效，请重新登录",
        );
        if ((ret ?? false) && context.mounted) {
          final storage = getProvider(authStorageProvider.notifier);
          await storage.clear();
        }
      }
    });
  }

  @override
  void dispose() {
    // _linkSubscription?.cancel();

    super.dispose();
  }

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return ScreenUtilInit(
      designSize: const Size(375, 812), // 设计稿尺寸（默认 iPhoneX 375x812）
      minTextAdapt: true, // 是否根据宽度/高度适配文字
      splitScreenMode: true, // 支持分屏尺寸
      builder: (context, child) {
        return MaterialApp.router(
          routerConfig: appRouter.config(
            navigatorObservers: () => [NativeRouteObserver()],
          ),
          theme: AppTheme.lightTheme,
          darkTheme: AppTheme.lightTheme,
          themeMode: ThemeMode.light,
        );
      },
    );
  }
}

void _initLog() {
  // 初始化日志系统
  final fileOutput = LogFileOutput();
  Log.init(isProduction: kReleaseMode, outputs: [fileOutput]);
  Log.i("日志系统初始化完成。");

  // 4. 设置全局的 Flutter 和 Dart 错误处理器
  FlutterError.onError = (details) {
    Log.e('捕获到 Flutter 框架错误', details.exception, details.stack);
    // 注意：在生产环境中，你可能不想每次都退出应用
    fileOutput.ensureAllWritten(); //.then((_) => exit(1));
  };

  PlatformDispatcher.instance.onError = (error, stack) {
    Log.e('捕获到未处理的 Dart (Isolate) 错误', error, stack);
    fileOutput.ensureAllWritten(); //.then((_) => exit(1));
    return true; // 表示错误已被处理
  };
  Log.i("全局错误处理器设置完成。");
}
